/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.workflow.service.user.userParser;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.je.bpm.core.model.config.task.assignment.AssigneeResource;
import com.je.bpm.core.model.config.task.assignment.BasicAssignmentConfigImpl;
import com.je.bpm.core.model.config.task.assignment.PersonnelMatrixConfigImpl;
import com.je.bpm.core.model.task.KaiteBaseUserTask;
import com.je.bpm.runtime.shared.identity.UserDepartmentManager;
import com.je.bpm.runtime.shared.identity.UserFormFieldsManager;
import com.je.bpm.runtime.shared.identity.UserRoleManager;
import com.je.common.base.DynaBean;
import com.je.common.base.mapper.query.NativeQuery;
import com.je.common.base.service.MetaRbacService;
import com.je.common.base.spring.SpringContextHolder;
import com.je.core.entity.extjs.JSONTreeNode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 人员矩阵
 */
public class PersonnelMatrixParser extends AbstractUserParser {

    @Override
    public JSONTreeNode parser(String userId,
                               BasicAssignmentConfigImpl basicAssignmentConfig, KaiteBaseUserTask kaiteBaseUserTask,
                               Boolean showCompany,
                               Map<String, Object> bean, String prod, Boolean multiple, Boolean addOwn, Map<String, String> customerMap) {
        MetaRbacService metaRbacService = SpringContextHolder.getBean(MetaRbacService.class);
        PersonnelMatrixConfigImpl personnelMatrixConfig = (PersonnelMatrixConfigImpl) basicAssignmentConfig;
        PersonnelMatrixConfigImpl.Config config = personnelMatrixConfig.getConfig();
        String matrixId = config.getMatrixId();
        //结果字段id
        String resultFieldId = config.getResultFieldId();
        List<PersonnelMatrixConfigImpl.Config.ConditionalInfo> conditionalInfos = config.getConditionalInfos();

        if (conditionalInfos.size() == 0 || Strings.isNullOrEmpty(resultFieldId)) {
            return null;
        }

        DynaBean dynaBean = metaRbacService.selectOneByPk("JE_RBAC_MATRIX", matrixId);
        if (dynaBean.getStr("MATRIX_SFJY").equals("1")) {
            return null;
        }

        List<DynaBean> list = metaRbacService.selectByNativeQuery(NativeQuery.build().tableCode("JE_RBAC_MATRIX_DATA")
                .eq("JE_RBAC_MATRIX_ID", matrixId));
        if (list.size() == 0) {
            return null;
        }

        Map<String, Object> values = new HashMap<>();
        for (PersonnelMatrixConfigImpl.Config.ConditionalInfo conditionalInfo : conditionalInfos) {
            String id = conditionalInfo.getCondition();
            String value = conditionalInfo.getConditionValue();
            String valueKey = value.replace("{", "").replace("}", "");
            if (bean.get(valueKey) == null) {
                values.put(id, "");
            } else {
                values.put(id, bean.get(valueKey));
            }
        }

        if (values.size() == 0) {
            return null;
        }

        String resultValue = "";
        String resultType = "";
        //列表list
        for (DynaBean matrix : list) {
            boolean isCompare = true;
            String jzsjStr = matrix.getStr("DATA_JZSJ");
            if (Strings.isNullOrEmpty(jzsjStr)) {
                continue;
            }
            JSONObject jzsjJson = JSONObject.parseObject(jzsjStr);
            for (String key : values.keySet()) {
                if (!String.valueOf(values.get(key)).equals(String.valueOf(jzsjJson.get(key)))) {
                    isCompare = false;
                    break;
                }
            }

            if (isCompare) {
                resultValue = jzsjJson.getString(resultFieldId + "_id");
                resultType = jzsjJson.getString(resultFieldId + "_type");
                break;
            }
        }

        Object child = null;

        if (resultType.equals("user")) {
            UserFormFieldsManager userFormFieldsManager = SpringContextHolder.getBean(UserFormFieldsManager.class);
            child = userFormFieldsManager.findUsers(Arrays.asList(resultValue.split(",")), multiple, addOwn);
        }

        if (resultType.equals("department")) {
            UserDepartmentManager userDepartmentManager = SpringContextHolder.getBean(UserDepartmentManager.class);
            child = userDepartmentManager.findUserDepts(userId, resultValue, assignmentPermissionBo, showCompany, multiple, addOwn);
        }

        if (resultType.equals("role")) {
            UserRoleManager userRoleManager = SpringContextHolder.getBean(UserRoleManager.class);
            child = userRoleManager.findUserRoles(userId, resultValue, assignmentPermissionBo, showCompany, multiple, addOwn);
        }
        if (child != null && child instanceof JSONTreeNode) {
            return (JSONTreeNode) child;
        }

        return null;
    }

    @Override
    public Boolean analysis(String userId, BasicAssignmentConfigImpl basicAssignmentConfig, KaiteBaseUserTask kaiteBaseUserTask,
                            Map<String, Object> bean, String prod, Map<String, String> customerMap) {
        UserDepartmentManager userDepartmentManager = SpringContextHolder.getBean(UserDepartmentManager.class);
        buildAssignmentPermissionBo(basicAssignmentConfig.getPermission(), bean);
        List<AssigneeResource> assigneeResourceList = basicAssignmentConfig.getResource();
        String deptIds = assigneeResourceList.stream().map(assigneeResource -> assigneeResource.getId())
                .collect(Collectors.joining(","));
        return userDepartmentManager.checkContainsCurrentUser(userId, deptIds, assignmentPermissionBo);
    }


}
